﻿using Payroll.Biz.Legacy.DAL;
using Payroll.Biz.Legacy.Exceptions;
using Payroll.Biz.Legacy.Models;
using Payroll.Biz.Legacy.ServiceParams;
using Payroll.Biz.Legacy.Utils;
using System;
using System.Linq;

namespace Payroll.Biz.Legacy.Services
{
    public class AddHourlyEmployeeService : AbstractService, IService<AddHourlyEmployeeServiceParams>
    {
        public AddHourlyEmployeeService(IPayrollDatabase database) : base(database)
        {
        }

        public ServiceResult Execute(AddHourlyEmployeeServiceParams serviceParams)
        {
            try
            {
                ValidateInput(serviceParams);

                IPaymentClassification paymentClassification = new HourlyClassification(serviceParams.HourlyRate);

                Guid id = Guid.NewGuid();

                Employee employee = EmployeeFactory.Create(
                    id,
                    serviceParams.Name,
                    serviceParams.Address,
                    paymentClassification);
                employee.Schedule = new WeeklySchedule();
                employee.Method = new HoldMethod();

                Database.AddEmployee(employee);

                return ServiceResult.CreateSuccessResult(employee.Id);
            }
            catch (Exception ex)
            {
                return ServiceResult.CreateErrorResult(ex.Message, ex);
            }
        }

        private static void ValidateInput(AddHourlyEmployeeServiceParams serviceParams)
        {
            if (serviceParams == null)
            {
                throw new ArgumentNullException(nameof(serviceParams));
            }

            if (string.IsNullOrEmpty(serviceParams.Name))
            {
                throw new ServiceException(string.Format("{0} cannot be null or empty.", nameof(serviceParams.Name)));
            }

            if (string.IsNullOrEmpty(serviceParams.Address))
            {
                throw new ServiceException(string.Format("{0} cannot be null or empty.", nameof(serviceParams.Address)));
            }

            if (serviceParams.HourlyRate <= 0m)
            {
                throw new ServiceException(
                    string.Format("{0} cannot be less than or equals to 0.", nameof(serviceParams.HourlyRate)));
            }
        }
    }
}
